import {toast} from "../../utils/tool";

const app = getApp()
Page({
    data: {
        activeTab: 0,
        tabRect: [0, 0],
        tabList: [
            {
                label: '可领取',
                value: 0
            },
            {
                label: '我拥有',
                value: 1,
            }
        ],
        list: [],
    },

    changeTab(ev) {
        const {tab} = ev.currentTarget.dataset
        const value = tab * 1
        if (this.data.activeTab === value) return
        this.setData({
            activeTab: tab
        })
    },
    swiperChange(ev) {
        const {current} = ev.detail
        this.setData({
            activeTab: current
        })
    },
    initRect() {
        let selector = wx.createSelectorQuery().in(this)
        // selector.select('#tabConn').boundingClientRect()
        selector.selectAll('#tabConn .tab-item').boundingClientRect()
        selector.select('#tabConn .tab-slide').boundingClientRect()
        selector.exec(result => {
            const [items, slide] = result
            const {width: slideWidth} = slide
            const resp = items.map(item => {
                return item.left + (item.width / 2) - (slideWidth / 2)
            })
            this.setData({
                tabRect: resp,
            })
        })
    },
    onReady() {
        this.initRect()
    },
    formatDate(time) {
        const date = new Date(time * 1000)
        const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
        return `${year}-${month < 10 ? '0' + month : month}-${day >= 10 ? day : '0' + day}`
    },
    toUseCoupon(){
      wx.switchTab({
          url:'/pages/index/index'
      })
    },
    initData() {
        app.ajax({
            url: '/api/user/coupons',
            success: resp => {
                console.log(resp, 'resp')
                const {code, data, msg} = resp
                if (code !== 1) {
                    return toast({
                        title: msg
                    }, () => {
                        wx.navigateBack()
                    })
                }
                if (data && data.length) {
                    const result = data.map(item => {
                        const createTime = this.formatDate(item['create_time'])
                        return {
                            ...item,
                            createTime,
                        }
                    })
                    console.log(result, 'result')
                    this.setData({
                        list: result,
                    })
                }
            }
        })
    },
    onLoad: function (options) {
        this.initData()
    }
});
